//
//  PublishArticleViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/18.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "PublishArticleViewController.h"
#import "ArticleHeaderCell.h"
#import "ArticleBottomViewCell.h"
#import "ArticleTextViewCell.h"
#import "ArticleTextImgViewCell.h"
#import "ArticleModel.h"
#import "GCQiniuUploadManager.h"
#import "RichTextViewController.h"
#import "IQKeyboardManager.h"

@interface PublishArticleViewController () <UITableViewDelegate, UITableViewDataSource, ArticleHeaderDelegate, UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSString *docid;
@property (strong, nonatomic) UIImage *coverimg;
@property (strong, nonatomic) NSString *coverid;
@property (strong, nonatomic) NSString *coverurl;
@property (strong, nonatomic) NSMutableArray *textArray;
@property (strong, nonatomic) NSMutableArray *imgurlArray;
@property (strong, nonatomic) NSMutableArray *imgidArray;
@property (strong, nonatomic) NSMutableArray *textSortIndex;
@property (strong, nonatomic) NSMutableArray *imgSortIndex;

@end

@implementation PublishArticleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [PublishData sharedPublishData].chooseTribeID = @"";
    [PublishData sharedPublishData].chooseTribeName = @"";
    
    [[PublishData sharedPublishData].localArray removeAllObjects];
    self.coverimg = nil;
    ArticleModel *baseone = [ArticleModel new];
    baseone.type = ArticleModelTxt;
    baseone.txt = @"";
    [[PublishData sharedPublishData].localArray addObject:baseone];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    if (self.mytype == PublishArticleNormal) {
        self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"发布文章"];
    } else {
        self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"创建故事"];
    }
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *button = [ViewFactory makeNavigationTextButtonWhite:@"发布"];
    [button addTarget:self action:@selector(goPublish) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightButton;
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)goPop {
    [self.view endEditing:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定要取消吗？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { //确定
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)goPublish {
    [self.view endEditing:YES];
//    RichTextViewController *demo = [[RichTextViewController alloc] init];
//    [self.navigationController pushViewController:demo animated:YES];
    if ([PublishData sharedPublishData].pubtitle.length == 0) {
        [ViewFactory showInfoMsg:@"请输入标题！"];
        return;
    }
    
    if ([PublishData sharedPublishData].pubdesc.length == 0) {
        [ViewFactory showInfoMsg:@"请输入描述！"];
        return;
    }
    
    if ([[PublishData sharedPublishData].chooseTribeID isEqualToString:@""]) {
        [ViewFactory showInfoMsg:@"请选择部落！"];
        return;
    }
    
    if (self.coverimg != nil) {
        [ViewFactory showLoading];
        [self uploadCover];
    } else {
        [ViewFactory showInfoMsg:@"请选择封面图!"];
        return;
    }
}

- (void)uploadCover {
    NSData *coverdata = UIImageJPEGRepresentation(self.coverimg, HIGHSIZE);
    [[GCQiniuUploadManager sharedInstance] uploadData:coverdata progress:^(float percent) {
    } completion:^(NSError *error, NSString *link, NSInteger index) {
        if (link == nil) {
            [ViewFactory showErrorStrMsg:@"上传失败！"];
            return;
        }
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
            self.coverid = link;
            self.coverurl = resurl;
            [self uploadImages];
        }
    }];
}

- (void)uploadImages {
    [self.textArray removeAllObjects];
    [self.imgurlArray removeAllObjects];
    [self.imgidArray removeAllObjects];
    [self.imgSortIndex removeAllObjects];
    [self.textSortIndex removeAllObjects];
    NSMutableArray *dataarray = [NSMutableArray new];
    NSInteger startindex = 1; //startindex 0 is cover
    for (NSInteger i = 0; i < [PublishData sharedPublishData].localArray.count; i++) {
        ArticleModel *one = [PublishData sharedPublishData].localArray[i];
        if (one.type == ArticleModelImageTxt) {
            if (one.img) {
                NSData *imgdata = UIImageJPEGRepresentation(one.img, HIGHSIZE);
                [dataarray addObject:imgdata];
                [self.imgSortIndex addObject:[NSNumber numberWithInteger:startindex]];
                startindex++;
            }
            
            if (one.txt && one.txt.length > 0) {
                [self.textArray addObject:one.txt];
                [self.textSortIndex addObject:[NSNumber numberWithInteger:startindex]];
                startindex++;
            }
        } else {
            if (one.txt && one.txt.length > 0) {
                [self.textArray addObject:one.txt];
                [self.textSortIndex addObject:[NSNumber numberWithInteger:startindex]];
                startindex++;
            }
        }
    }
    
    if (dataarray.count > 0) {
        [[GCQiniuUploadManager sharedInstance] uploadDatas:dataarray progress:^(float percent) {
            
        } oneTaskCompletion:^(NSError *error, NSString *link, NSInteger index) {
            DYLog(@"upload index:%ld link:%@", index, link);
            if (link) {
                NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
                [self.imgurlArray addObject:resurl];
                [self.imgidArray addObject:link];
            }
        } allTasksCompletion:^{
            [self uploadDoc];
        }];
    } else {
        [self uploadDoc];
    }
}

- (void)uploadDoc {
//    NSString *coverid = @"";
//    if (self.imgidArray.count > 0) {
//        coverid = self.imgidArray[0];
//    }
    
    NSMutableArray *parray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.textArray.count; i++) {
        NSDictionary *pdict = @{
                                @"sort_index": self.textSortIndex[i],
                                @"md": self.textArray[i]
                                };
        [parray addObject:pdict];
    }
    
    NSMutableArray *picarray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.imgidArray.count; i++) {
        NSString *imgid = self.imgidArray[i];
        NSString *imgidurl = self.imgurlArray[i];
        NSDictionary *picdict = @{
                                  @"sort_index": self.imgSortIndex[i],
                                  @"id": imgidurl,
                                  @"media_type": @"00",
                                  @"tag": @[
                                          @{
                                              @"sort_index": @1,
                                              @"label_value": @"http://www.baidu.com",
                                              @"txt_orient": @"0",
                                              @"label_x": @"100",
                                              @"label_y": @"100",
                                              @"label_name": @"艺术1"
                                              },
                                          @{
                                              @"sort_index": @2,
                                              @"label_value": @"",
                                              @"txt_orient": @"0",
                                              @"label_x": @"200",
                                              @"label_y": @"200",
                                              @"label_name": @"艺术2"
                                              }
                                          ]
                                  };
        [picarray addObject:picdict];
    }
    
    NSDictionary *qndict =
    @{
      @"title": [PublishData sharedPublishData].pubtitle,
      @"desc": [PublishData sharedPublishData].pubdesc,
      @"cover_img": @{
              @"id": self.coverid,
              @"media_type": @"00",
              @"is_cover": @"00",
              @"tag": @[
                      @{
                          @"sort_index": @1,
                          @"label_value": @"http://www.baidu.com",
                          @"txt_orient": @"0",
                          @"label_x": @"100",
                          @"label_y": @"100",
                          @"label_name": @"艺术1"
                          },
                      @{
                          @"sort_index": @2,
                          @"label_value": @"",
                          @"txt_orient": @"0",
                          @"label_x": @"200",
                          @"label_y": @"200",
                          @"label_name": @"艺术2"
                          }
                      ]
              },
      @"content": @{
              @"paragraph": parray,
              @"img": picarray              }
      };
    
    NSData *qndata =[qndict JSONData];
    [[GCQiniuUploadManager sharedInstance] uploadData:qndata progress:^(float percent) {
        DYLog(@"upload percent:%f", percent);
    } completion:^(NSError *error, NSString *link, NSInteger index) {
        if (link == nil) {
            [ViewFactory showErrorStrMsg:@"上传失败！"];
            return;
        }
        
        DYLog(@"upload link:%@", link);
        NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
        self.docid = resurl;
        [self publishTopic];
    }];
}

- (void)publishTopic {
    //content_type：00话题 01文章 is_cover:00封面图 01非封面图 media_type:00
    NSMutableArray *picarray = [[NSMutableArray alloc] init];
    
    NSDictionary *picdictone = @{
                              @"is_cover": @"00",
                              @"media_id": self.coverid,
                              @"media_size": @0,
                              @"media_type": @"00",
                              @"media_url": self.coverurl,
                              @"sortindex": [NSNumber numberWithInteger:0],
                              @"tag": @[
                                      @{
                                          @"label_type": @"string",
                                          @"label_value": @"string",
                                          @"label_x": @"string",
                                          @"label_y": @"string",
                                          @"sortindex": @0,
                                          @"txt_orient": @"string"
                                          }
                                      ]
                              };
    [picarray addObject:picdictone];
    
    for (NSInteger i = 0; i < self.imgidArray.count; i++) {
        NSString *iscover = @"01";
        NSString *imgid = self.imgidArray[i];
        NSString *imgurl = self.imgurlArray[i];
        NSDictionary *picdict = @{
                                  @"is_cover": iscover,
                                  @"media_id": imgurl,
                                  @"media_size": @0,
                                  @"media_type": @"00",
                                  @"media_url": imgurl,
                                  @"sortindex": self.imgSortIndex[i],
                                  @"tag": @[
                                          @{
                                              @"label_type": @"string",
                                              @"label_value": @"string",
                                              @"label_x": @"string",
                                              @"label_y": @"string",
                                              @"sortindex": @0,
                                              @"txt_orient": @"string"
                                              }
                                          ]
                                  };
        [picarray addObject:picdict];
    }
    
    NSString *tribeid = @"0";
    if ([PublishData sharedPublishData].chooseTribeID.length > 0) {
        tribeid = [PublishData sharedPublishData].chooseTribeID;
    }
    NSDictionary *textdict = @{
                               @"content_id": @0,
                               @"content_type": @"01",
                               @"coverImg": self.coverurl,
                               @"desc": [PublishData sharedPublishData].pubdesc,
                               @"doc_id": self.docid,
                               @"media": picarray,
                               @"title": [PublishData sharedPublishData].pubtitle,
                               @"tribe_id": tribeid,
                               @"user_id": [UserData userid]
                               };
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/hyContent/saveContent",APIYIGOU];
    if (self.mytype == PublishArticleStory) {
        urlStr = [NSString stringWithFormat:@"%@/hyContent/saveContentAndMyStroy",APIYIGOU];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[UserData usertoken] forHTTPHeaderField:@"Auth"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    [manager POST:urlStr parameters:textdict success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
        if ([[dict valueForKey:@"code"] intValue] == 100) {
            [ViewFactory showSuccess:@"发布成功！"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [ViewFactory showErrorStrMsg:@"发布失败！"];
        }
        DYLog(@"result:%@", dict.description);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error %ld",(long)error.code);
        [ViewFactory showErrorStrMsg:@"发布失败！"];
    }];
}

- (void)refreshTable {
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2 + [PublishData sharedPublishData].localArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 300;
    } else if (indexPath.row > 0 && indexPath.row <= [PublishData sharedPublishData].localArray.count) {
        ArticleModel *localone = [[PublishData sharedPublishData].localArray objectAtIndex:indexPath.row - 1];
        return 120;
//        if (localone.type == ArticleModelTxt) {
//            return 120;
//        }
//        return 150;
    } else if (indexPath.row == [PublishData sharedPublishData].localArray.count + 1) {
        return 120;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        ArticleHeaderCell *cell = GET_CELL(ArticleHeaderCell, @"ArticleHeaderCell");
        cell.delegate = self;
        return cell;
    } else if (indexPath.row > 0 && indexPath.row <= [PublishData sharedPublishData].localArray.count) {
        ArticleModel *localone = [[PublishData sharedPublishData].localArray objectAtIndex:indexPath.row - 1];
        if (localone.type == ArticleModelTxt) {
            ArticleTextViewCell *cell = GET_CELL(ArticleTextViewCell, @"ArticleTextViewCell");
            cell.contentTextView.text = localone.txt;
            cell.controller = self;
            cell.dataIndex = indexPath.row - 1;
            return cell;
        } else if (localone.type == ArticleModelImageTxt) {
            ArticleTextImgViewCell *cell = GET_CELL(ArticleTextImgViewCell, @"ArticleTextImgViewCell");
            cell.img.image = localone.img;
            cell.contentTextView.text = localone.txt;
            cell.controller = self;
            cell.dataIndex = indexPath.row - 1;
            cell.tagbg.hidden = YES;
            return cell;
        }
        return nil;
    } else if (indexPath.row == [PublishData sharedPublishData].localArray.count + 1) {
        ArticleBottomViewCell *cell = GET_CELL(ArticleBottomViewCell, @"ArticleBottomViewCell");
        cell.controller = self;
        return cell;
    }
    return nil;
}

-(BOOL)tableView:(UITableView *) tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    //打开编辑
    return YES;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    //允许移动
    return YES;
    //return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    if (sourceIndexPath == destinationIndexPath ) return;
    
    NSInteger source = sourceIndexPath.row;
    NSInteger dest = destinationIndexPath.row;
    
    [self.tableView beginUpdates];
    ArticleModel *model = [PublishData sharedPublishData].localArray[source];
    [[PublishData sharedPublishData].localArray removeObjectAtIndex:source];
    [[PublishData sharedPublishData].localArray insertObject:model atIndex:dest];
    [self.tableView endUpdates];
    
    [tableView reloadData];
}

- (void)updateTable:(NSInteger)sourceIndex newIndex:(NSInteger)destIndex {
    if (sourceIndex == destIndex)
        return;
    NSIndexPath *preindex = [NSIndexPath indexPathForRow:sourceIndex inSection:0];
    NSIndexPath *nowindex = [NSIndexPath indexPathForRow:destIndex inSection:0];
    [self tableView:self.tableView moveRowAtIndexPath:preindex toIndexPath:nowindex];
}

- (void)articleHeaderChooseOne:(UIImage *)image {
    self.coverimg = image;
}

ARRAY_INIT(textArray)
ARRAY_INIT(imgurlArray)
ARRAY_INIT(imgidArray)
ARRAY_INIT(textSortIndex)
ARRAY_INIT(imgSortIndex)

@end
